<script setup>
import {ref} from "vue";
import AccountTop from "@/components/AccountTop.vue";
import AccountBg from "@/components/AccountBg.vue";
import {httpGet, httpPost} from "@/utils/http";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";
import SendMsg from "@/components/SendMsg.vue";
import {arrayContains, isMobile} from "@/utils/libs";
import {setUserToken} from "@/store/session";
import {validateEmail, validateMobile} from "@/utils/validate";
import {showMessageError, showMessageOk} from "@/utils/dialog";
import {getSystemInfo} from "@/store/cache";

const router = useRouter()
const title = ref('')
const logo = ref('')

const data = ref({
  username: '', // 用户名
  password: '', // 密码
  mobile: '', // 手机号
  email: '', // 邮箱
  repass: '', // 重复密码
  code: '', // 验证码
  invite_code: router.currentRoute.value.query['invite_code'] // 邀请码，从url路径中获取参数
})

// mobile、email、username 注册方式是否开启
const enableMobile = ref(false)
const enableEmail = ref(false)
const enableUser = ref(false)
// 是否开启注册
const enableRegister = ref(true)
// 注册类型：mobile、email、username
const activeName = ref('mobile')
// 微信图片，如果没有开启注册就显示微信图片，让用户添加微信
const wxImg = ref('/images/wx.png')

// 记录邀请码点击次数
if (data.value.invite_code) {
  httpGet('api/invite/hits', {code: data.value.invite_code})
}

// 获取系统配置
getSystemInfo().then(res => {
  if (res.data) {
    title.value = res.data.title
    logo.value = res.data.logo
    // 获取注册方式
    const registerWays = res.data['register_ways']
    // 判断用户名注册是否开启
    if (arrayContains(registerWays, 'username')) {
      enableUser.value = true
      activeName.value = 'username'
    }
    // 判断邮箱注册是否开启
    if (arrayContains(registerWays, 'email')) {
      enableEmail.value = true
      activeName.value = 'email'
    }
    // 判断手机号注册是否开启
    if (arrayContains(registerWays, 'mobile')) {
      enableMobile.value = true
      activeName.value = 'mobile'
    }
    // 是否开启注册
    enableRegister.value = res.data['enabled_register']
    // 使用后台上传的客服微信二维码
    if (res.data['wechat_card_url'] !== '') {
      wxImg.value = res.data['wechat_card_url']
    }
  }
}).catch(e => {
  ElMessage.error('获取系统配置失败：' + e.message)
})

// 点击注册回调方法
const submitRegister = () => {
  if (activeName.value === 'username' && data.value.username === '') {
    return ElMessage.error('请输入用户名')
  }

  if (activeName.value === 'mobile' && !validateMobile(data.value.mobile)) {
    return ElMessage.error('请输入合法的手机号')
  }

  if (activeName.value === 'email' && !validateEmail(data.value.email)) {
    return ElMessage.error('请输入合法的邮箱地址')
  }

  if (data.value.password.length < 8) {
    return ElMessage.error('密码的长度为8-16个字符')
  }

  if (data.value.password !== data.value.repass) {
    return ElMessage.error('两次输入密码不一致')
  }

  if ((activeName.value === 'mobile' || activeName.value === 'email') && data.value.code === '') {
    return ElMessage.error('请输入验证码');
  }
  // 发生请求
  doRegister()
}

// 发送注册请求
const doRegister = () => {
  data.value.reg_way = activeName.value
  httpPost('api/user/register', data.value).then(res => {
    // 存储token
    setUserToken(res.data.token)
    showMessageOk("注册成功，即将跳转到对话主界面...")
    if (isMobile()) {
      router.push('/mobile/index')
    } else {
      router.push('/chat')
    }
  }).catch(e => {
    showMessageError('注册失败：' + e.message)
  })
}

</script>

<template>
  <div>
    <div class="flex-center loginPage">
      <div class="left" v-if="enableRegister">
        <div class="login-box">
          <AccountTop title="注册"/>
          <div class="input-form">
            <el-form :model="data" class="form">
              <el-tabs v-model="activeName">
                <el-tab-pane label="手机注册" name="mobile" v-if="enableMobile">
                  <el-form-item>
                    <div class="form-title">手机号码</div>
                    <el-input placeholder="请输入手机号码" size="large" v-model="data.mobile" maxlength="11" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item>
                    <div class="form-title">验证码</div>
                    <div class="flex w100">
                      <el-input placeholder="请输入验证码" size="large" maxlength="30" class="code-input" v-model="data.code" autocomplete="off"></el-input>
                      <send-msg size="large" :receiver="data.mobile" type="mobile"/>
                    </div>
                  </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="邮箱注册" name="email" v-if="enableEmail">
                  <el-form-item class="block">
                    <div class="form-title">邮箱</div>
                    <el-input placeholder="请输入邮箱地址" size="large" v-model="data.email" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item class="block">
                    <div class="form-title">验证码</div>
                    <div class="flex w100">
                      <el-input placeholder="请输入验证码" size="large" maxlength="30" class="code-input" v-model="data.code" autocomplete="off"></el-input>
                      <send-msg size="large" :receiver="data.email" type="email"/>
                    </div>
                  </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="用户名注册" name="username" v-if="enableUser">
                  <el-form-item class="block">
                    <div class="form-title">用户名</div>
                    <el-input placeholder="请输入用户名" size="large" v-model="data.username" autocomplete="off"></el-input>
                  </el-form-item>
                </el-tab-pane>
              </el-tabs>

              <el-form-item class="block">
                <div class="form-title">密码</div>
                <el-input placeholder="请输入密码(8-16位)" maxlength="16" size="large" v-model="data.password" show-password autocomplete="off"></el-input>
              </el-form-item>

              <el-form-item class="block">
                <div class="form-title">重复密码</div>
                <el-input placeholder="请再次输入密码(8-16位)" maxlength="16" size="large" v-model="data.repass" show-password autocomplete="off"></el-input>
              </el-form-item>

              <el-form-item class="block">
                <div class="form-title">邀请码</div>
                <el-input placeholder="请输入邀请码(可选)" size="large" v-model="data.invite_code" autocomplete="off"></el-input>
              </el-form-item>

              <el-row class="btn-row" :gutter="20">
                <el-col :span="24">
                  <el-button class="login-btn" type="primary" size="large" @click="submitRegister">注册</el-button>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>
      </div>

      <div class="tip-result left" v-else>
        <el-result icon="error" title="注册功能已关闭">
          <template #sub-title>
            <p>抱歉，系统已关闭注册功能，请联系管理员添加账号！</p>
            <div class="wechat-card">
              <el-image :src="wxImg"/>
            </div>
            <div class="mt-3">
              <el-button type="primary" @click="router.push('/')"><i class="iconfont icon-home mr-1"></i> 返回首页</el-button>
            </div>
          </template>
        </el-result>
      </div>
      <account-bg/>
    </div>
  </div>
</template>

<style lang="stylus" scoped>
@import "../assets/css/login.styl"
:deep(.back) {
  margin-bottom: 10px;
}

:deep(.orline) {
  margin-bottom: 10px;
}

.wechat-card {
  margin-top: 20px

}
</style>